package base.impl

import base.IPipeStream
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter

/**
 * A file output stream that writes data to a file.
 */
class PipeFileOutputStream<T> : IPipeStream<T> {

    private var mFileWriter: FileWriter? = null
    private var bufferWriter: BufferedWriter? = null
    private val mFile: File

    constructor(file: File) {
        this.mFile = file
    }

    constructor(fileName: String) {
        this.mFile = File(fileName)
    }

    override fun open() {
        if (!mFile.parentFile.exists()) {
            mFile.parentFile.mkdirs()
        }

        mFileWriter = FileWriter(mFile, false)
        bufferWriter = BufferedWriter(mFileWriter!!)
    }

    override fun close() {
        bufferWriter?.close()
    }

    override fun write(list: MutableList<T>) {
        list.forEach {
            bufferWriter?.write(it.toString())
            bufferWriter?.write("\r\n")
        }
    }
}